package com.ermax.aircond.manage.web.bean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ermax.aircond.common.parameter.Status;
import com.ermax.aircond.maintain.domain.Building;
import com.ermax.aircond.maintain.domain.Floor;
import com.ermax.aircond.maintain.domain.Machine;
import com.ermax.aircond.maintain.domain.Room;
import com.ermax.aircond.maintain.service.MaintainService;
import com.ermax.aircond.manage.domain.ScheduleTerm;
import com.ermax.aircond.manage.service.ScheduleControlService;
import com.ermax.aircond.resource.MessageBundle;
import com.ermax.aircond.util.web.bean.DataTableBean;


public class ScheduleManageBeanBAK extends DataTableBean implements java.io.Serializable {
	
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(ScheduleManageBeanBAK.class);
	private static final String STATUS_INIT = "INIT";
	private static final String STATUS_SEARCH = "SEARCH";
	private static final String STATUS_SELECT = "SELECT";
	private static final String STATUS_CONTROL = "CONTROL";
	

	@Resource(name = "maintainService")
	private MaintainService maintainService;
	@Resource(name = "scheduleControlService")
	private ScheduleControlService scheduleControlService;

	private List<SelectItem> buildingOptions = new ArrayList<SelectItem>();
	private List<SelectItem> floorOptions = new ArrayList<SelectItem>();
	private List<SelectItem> roomOptions = new ArrayList<SelectItem>();
	private List<SelectItem> machineOptions = new ArrayList<SelectItem>();
	
	
	private long selectedBuildingId;
	private long selectedFloorId;
	private long selectedRoomId;
	private long selectedMachineId;
	private long selectedScheduleTermId;
	
	private List<Machine> selectedMachines = new ArrayList<Machine>();
	private Map<Machine, List<ScheduleTerm>> machineMap = new LinkedHashMap<Machine, List<ScheduleTerm>>();
	
	private ScheduleTerm editItem = new ScheduleTerm();
		
	
	//Options
	private List<SelectItem> minimumTemperatureOptions = new ArrayList<SelectItem>();
	private List<SelectItem> temperatureOptions = new ArrayList<SelectItem>();
	private List<SelectItem> hourOptions = new ArrayList<SelectItem>();
	private List<SelectItem> minuteOptions = new ArrayList<SelectItem>();

	private String status = "";
	
	@PostConstruct
	public void init() {
		try {
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_init_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}

	private void reset() throws Exception {
		hourOptions = createHourOptions();
		minuteOptions = createMinuteOptions();
		buildingOptions = createBuildingOptions();
		floorOptions = createFloorOptions();
		roomOptions = createRooomOptions();
		machineOptions = createMachineOptions();
		temperatureOptions = createTemperatureOptions();
		minimumTemperatureOptions = createMinimumTemperatureOptions();
		
		setEditItem(new ScheduleTerm());
		status = STATUS_INIT;
		selectedMachines.clear();
		machineMap.clear();
	}

	
	
	
	public void searchDetail(){	
		selectedMachines.clear();
		machineMap.clear();
		boolean valid = true;
		
		if(selectedBuildingId <= 0){			
			StringBuilder sb = new StringBuilder();
			sb.append(MessageBundle.getInstance().getMessage("building_name", FacesContext.getCurrentInstance().getViewRoot().getLocale()));
			sb.append("-");
			sb.append(MessageBundle.getInstance().getMessage("required_field", FacesContext.getCurrentInstance().getViewRoot().getLocale()));			
			FacesMessage facesMessage = new FacesMessage(sb.toString());
			FacesContext.getCurrentInstance().addMessage("search_building_name", facesMessage);
			valid = false;
		}
		
		if(selectedFloorId <= 0){			
			StringBuilder sb = new StringBuilder();
			sb.append(MessageBundle.getInstance().getMessage("floor_name", FacesContext.getCurrentInstance().getViewRoot().getLocale()));
			sb.append("-");
			sb.append(MessageBundle.getInstance().getMessage("required_field", FacesContext.getCurrentInstance().getViewRoot().getLocale()));			
			FacesMessage facesMessage = new FacesMessage(sb.toString());
			FacesContext.getCurrentInstance().addMessage("search_floor_name", facesMessage);
			valid = false;
		}
		
		if(selectedRoomId <= 0){			
			StringBuilder sb = new StringBuilder();
			sb.append(MessageBundle.getInstance().getMessage("room_name", FacesContext.getCurrentInstance().getViewRoot().getLocale()));
			sb.append("-");
			sb.append(MessageBundle.getInstance().getMessage("required_field", FacesContext.getCurrentInstance().getViewRoot().getLocale()));			
			FacesMessage facesMessage = new FacesMessage(sb.toString());
			FacesContext.getCurrentInstance().addMessage("search_room_name", facesMessage);
			valid = false;
		}
		if(!valid){
			return;
		}
		status = STATUS_CONTROL;
		// search by machine
		if (selectedMachineId > 0) {
			try {
				Machine machine = maintainService.getMachineById(selectedMachineId);
				List<ScheduleTerm> scheduleTerms = scheduleControlService.getScheduleTerm(machine);
				
				selectedMachines.add(machine);
				machineMap.put(machine, scheduleTerms);
			} catch (Exception e) {
				logger.error(e.getLocalizedMessage());
			}	
			return;
		}

		// search by room
		if (selectedRoomId > 0) {
			try {
				Room room = maintainService.getRoomById(selectedRoomId);
				List<Machine> machines = maintainService.getMachines(null, null, room, null, Status.ACTIVE);				
				Iterator<Machine> iter = machines.iterator();
				while(iter.hasNext()){
					Machine machine = iter.next();
					List<ScheduleTerm> scheduleTerms = scheduleControlService.getScheduleTerm(machine);
					selectedMachines.add(machine);
					machineMap.put(machine, scheduleTerms);
				}
 			} catch (Exception e) {
				logger.error(e.getLocalizedMessage());
			}
			return;
		}			
		
	}
	
	public void create(){
		try{				
			if(selectedMachineId < 0){
				String message = MessageBundle.getInstance().getMessage("error_create_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale()); 
				FacesMessage facesMessage  = new FacesMessage(message);
				FacesContext.getCurrentInstance().addMessage(null,facesMessage);
				return;
			}
			Machine machine = maintainService.getMachineById(selectedMachineId);
			editItem.setMachine(machine);
			scheduleControlService.createSchedule(editItem);
			editItem = new ScheduleTerm();
			searchDetail();
		}catch(Exception ex){
			
		}
	}

	
	public void update(){
		try {
			scheduleControlService.updateSchedule(editItem);
			searchDetail();
		} catch (Exception e) {
			String message = MessageBundle.getInstance().getMessage("error_update_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
		
	}
	
	public void remove(){
		try {
			scheduleControlService.deleteSchedule(selectedScheduleTermId);
			searchDetail();
		} catch (Exception e) {
			String message = MessageBundle.getInstance().getMessage("error_remove_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}
	
	public void selectItem(){
		ScheduleTerm scheduleTerm;
		try {
			scheduleTerm = scheduleControlService.getScheduleTermById(selectedScheduleTermId);
			editItem = scheduleTerm;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}
	
	public void newItem(){
		editItem = new ScheduleTerm();
	}


	public void buildingValueChanged(ValueChangeEvent event) {
		if (null != event.getNewValue()) {
			selectedFloorId = 0;
			selectedRoomId = 0;
			selectedMachineId = 0;
			selectedBuildingId = (Long) event.getNewValue();
			floorOptions = createFloorOptions();
			roomOptions = createRooomOptions();
			machineOptions = createMachineOptions();
		}
	}

	public void floorValueChanged(ValueChangeEvent event) {
		if (null != event.getNewValue()) {
			selectedRoomId = 0;
			selectedMachineId = 0;
			selectedFloorId = (Long) event.getNewValue();
			roomOptions = createRooomOptions();
			machineOptions = createMachineOptions();
		}
	}

	public void roomValueChanged(ValueChangeEvent event) {
		if (null != event.getNewValue()) {
			selectedMachineId = 0;
			selectedRoomId = (Long) event.getNewValue();
			machineOptions = createMachineOptions();
		}
	}

	private List<SelectItem> createBuildingOptions() {
		List<SelectItem> results = new ArrayList<SelectItem>();
		results.add(new SelectItem(0,"------"));
		try {
			List<Building> buildings = maintainService.getAllBuildings(Status.ACTIVE);
			for (Building building : buildings) {
				SelectItem item = new SelectItem(building.getBuildingId(), building.getBuildingName());
				results.add(item);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return results;
	}

	private List<SelectItem> createFloorOptions() {
		List<SelectItem> results = new ArrayList<SelectItem>();
		results.add(new SelectItem(0,"------"));
		try {
			if (selectedBuildingId > 0) {
				Building selectedBuilding = maintainService.getBuildingById(selectedBuildingId);
				List<Floor> floors = maintainService.getFloors(selectedBuilding, null, Status.ACTIVE);
				for (Floor floor : floors) {
					SelectItem item = new SelectItem(floor.getFloorId(), floor.getFloorName());
					results.add(item);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return results;
	}

	private List<SelectItem> createRooomOptions() {
		List<SelectItem> results = new ArrayList<SelectItem>();
		results.add(new SelectItem(0,"------"));
		try {
			if (selectedFloorId > 0) {
				Floor selectedFloor = maintainService.getFloorById(selectedFloorId);
				List<Room> rooms = maintainService.getRooms(null, selectedFloor, null, Status.ACTIVE);
				for (Room room : rooms) {
					SelectItem item = new SelectItem(room.getRoomId(), room.getRoomName());
					results.add(item);
				}
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage());
		}
		return results;
	}

	private List<SelectItem> createMachineOptions() {
		List<SelectItem> results = new ArrayList<SelectItem>();
		results.add(new SelectItem(0,"ALL"));
		try {
			if (selectedRoomId > 0) {
				Room selectedRoom = maintainService.getRoomById(selectedRoomId);
				List<Machine> machines = maintainService.getMachines(null, null, selectedRoom, null, Status.ACTIVE);
				for (Machine machine : machines) {
					SelectItem item = new SelectItem(machine.getMachineId(), machine.getMachineName());
					results.add(item);
				}
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage());
		}
		return results;
	}
	
	private List<SelectItem> createHourOptions(){
		List<SelectItem> results = new ArrayList<SelectItem>();
		results.add(new SelectItem("00", "00"));
		results.add(new SelectItem("01", "01"));
		results.add(new SelectItem("02", "02"));
		results.add(new SelectItem("03", "03"));
		results.add(new SelectItem("04", "04"));
		results.add(new SelectItem("05", "05"));
		results.add(new SelectItem("06", "06"));
		results.add(new SelectItem("07", "07"));
		results.add(new SelectItem("08", "08"));
		results.add(new SelectItem("09", "09"));
		results.add(new SelectItem("10", "10"));
		results.add(new SelectItem("11", "11"));
		results.add(new SelectItem("12", "12"));
		results.add(new SelectItem("13", "13"));
		results.add(new SelectItem("14", "14"));
		results.add(new SelectItem("15", "15"));
		results.add(new SelectItem("16", "16"));
		results.add(new SelectItem("17", "17"));
		results.add(new SelectItem("18", "18"));
		results.add(new SelectItem("19", "19"));
		results.add(new SelectItem("20", "20"));
		results.add(new SelectItem("21", "21"));
		results.add(new SelectItem("22", "22"));
		results.add(new SelectItem("23", "23"));
		return results;	
	}
	
	private List<SelectItem> createMinuteOptions(){
		List<SelectItem> results = new ArrayList<SelectItem>();
		results.add(new SelectItem("00", "00"));
		results.add(new SelectItem("05", "05"));
		results.add(new SelectItem("10", "10"));
		results.add(new SelectItem("15", "15"));
		results.add(new SelectItem("20", "20"));
		results.add(new SelectItem("25", "25"));
		results.add(new SelectItem("30", "30"));
		results.add(new SelectItem("35", "35"));
		results.add(new SelectItem("40", "40"));
		results.add(new SelectItem("45", "45"));
		results.add(new SelectItem("50", "50"));
		results.add(new SelectItem("55", "55"));			
		return results;
	}
	
	private List<SelectItem> createTemperatureOptions(){
		List<SelectItem> results = new ArrayList<SelectItem>();
		for(int i=16; i<=32; i++){
			results.add(new SelectItem(i,String.valueOf(i)));
		}
		return results;
	}
	
	private List<SelectItem> createMinimumTemperatureOptions(){
		List<SelectItem> results = new ArrayList<SelectItem>();
		results.add(new SelectItem(0,String.valueOf(0)));
		for(int i=16; i<=32; i++){
			results.add(new SelectItem(i,String.valueOf(i)));
		}
		
		return results;
	}

	public MaintainService getMaintainService() {
		return maintainService;
	}

	public void setMaintainService(MaintainService maintainService) {
		this.maintainService = maintainService;
	}

	public List<SelectItem> getBuildingOptions() {
		return buildingOptions;
	}

	public void setBuildingOptions(List<SelectItem> buildingOptions) {
		this.buildingOptions = buildingOptions;
	}

	public List<SelectItem> getFloorOptions() {
		return floorOptions;
	}

	public void setFloorOptions(List<SelectItem> floorOptions) {
		this.floorOptions = floorOptions;
	}

	public List<SelectItem> getRoomOptions() {
		return roomOptions;
	}

	public void setRoomOptions(List<SelectItem> roomOptions) {
		this.roomOptions = roomOptions;
	}

	public List<SelectItem> getMachineOptions() {
		return machineOptions;
	}

	public void setMachineOptions(List<SelectItem> machineOptions) {
		this.machineOptions = machineOptions;
	}

	public long getSelectedBuildingId() {
		return selectedBuildingId;
	}

	public void setSelectedBuildingId(long selectedBuildingId) {
		this.selectedBuildingId = selectedBuildingId;
	}

	public long getSelectedFloorId() {
		return selectedFloorId;
	}

	public void setSelectedFloorId(long selectedFloorId) {
		this.selectedFloorId = selectedFloorId;
	}

	public long getSelectedRoomId() {
		return selectedRoomId;
	}

	public void setSelectedRoomId(long selectedRoomId) {
		this.selectedRoomId = selectedRoomId;
	}

	public long getSelectedMachineId() {
		return selectedMachineId;
	}

	public void setSelectedMachineId(long selectedMachineId) {
		this.selectedMachineId = selectedMachineId;
	}

	public ScheduleControlService getScheduleControlService() {
		return scheduleControlService;
	}

	public void setScheduleControlService(ScheduleControlService scheduleControlService) {
		this.scheduleControlService = scheduleControlService;
	}

	public ScheduleTerm getEditItem() {
		return editItem;
	}

	public void setEditItem(ScheduleTerm editItem) {
		this.editItem = editItem;
	}


	public List<SelectItem> getHourOptions() {
		return hourOptions;
	}

	public void setHourOptions(List<SelectItem> hourOptions) {
		this.hourOptions = hourOptions;
	}

	public List<SelectItem> getMinuteOptions() {
		return minuteOptions;
	}

	public void setMinuteOptions(List<SelectItem> minuteOptions) {
		this.minuteOptions = minuteOptions;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public List<Machine> getSelectedMachines() {
		return selectedMachines;
	}

	public void setSelectedMachines(List<Machine> selectedMachines) {
		this.selectedMachines = selectedMachines;
	}

	public List<SelectItem> getMinimumTemperatureOptions() {
		return minimumTemperatureOptions;
	}

	public void setMinimumTemperatureOptions(List<SelectItem> minimumTemperatureOptions) {
		this.minimumTemperatureOptions = minimumTemperatureOptions;
	}

	public List<SelectItem> getTemperatureOptions() {
		return temperatureOptions;
	}

	public void setTemperatureOptions(List<SelectItem> temperatureOptions) {
		this.temperatureOptions = temperatureOptions;
	}

	public Map<Machine, List<ScheduleTerm>> getMachineMap() {
		return machineMap;
	}

	public void setMachineMap(Map<Machine, List<ScheduleTerm>> machineMap) {
		this.machineMap = machineMap;
	}

	public long getSelectedScheduleTermId() {
		return selectedScheduleTermId;
	}

	public void setSelectedScheduleTermId(long selectedScheduleTermId) {
		this.selectedScheduleTermId = selectedScheduleTermId;
	}

}
